package com.itheima.reggie.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param employee
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<Employee> checkLogin(@RequestBody Employee employee, HttpSession session) {
        log.info("登录校验，用户信息{}", employee);
        //实现登录业务
        //1.将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.根据页面提交的用户名username查询数据库中员工数据信息
        LambdaUpdateWrapper<Employee> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee queryEmp = employeeService.getOne(wrapper);
        //3.如果没有查询到, 则返回登录失败结果
        if (queryEmp == null) {
            return R.error("用户名不存在");
        }
        //4.密码比对，如果不一致, 则返回登录失败结果
        String pwd = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if (!pwd.equals(queryEmp.getPassword())) {
            return R.error("密码错误");
        }
        //5.查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (queryEmp.getStatus() == 0) {
            return R.error("账号禁用");
        }
        //6.登录成功，将员工id存入Session, 并返回登录成功结果
        session.setAttribute("emp", queryEmp.getId());
        return R.success(queryEmp);

    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理Session中保存的当前员工id
        request.getSession().removeAttribute("emp");
        return R.success("退出成功");//code=1,退出成功，前端自动跳转到登录页面
    }

    /**
     * 添加员工
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工，员工信息：{}", employee.toString());
        long id = Thread.currentThread().getId();
        log.info("save*********************当前操作线程的id:{}",id);
        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //获得当前登录用户的id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateUser(empId);
//        employee.setCreateUser(empId);
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);
        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //执行查询
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改员工状态---更新员工信息和修改员工的状态
     * @param employee
     * @param session
     * @return
     */
    @PutMapping
    public R changeStatusEmp(@RequestBody Employee employee, HttpSession session) {
        log.info("changeStatus employee:{}", employee);
      //1.进一步封装需要更新的employee实体对象
        // 获取用户信息
     //        Long empId = (Long) session.getAttribute("emp");
     //更新用户状态，获取员工id
     //        employee.setUpdateUser(empId);//设置更新用户的用户id
     //        employee.setUpdateTime(LocalDateTime.now());//设置更新时间
        //2.更新员工信息
        employeeService.updateById(employee);
        return R.success("更新成功");
    }

    /**
     * 编辑员工信息--先查询后更新（更新和修改状态使用同一接口）
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> queryOneEmp(@PathVariable Long id){
        log.info("queryOneEmp employee:{}",id);
        //1.查询员工信息
        Employee emp = employeeService.getById(id);
        if (emp==null){
            return R.error("没有查询到对应的员工信息");

        }
        return R.success(emp);

    }





}





